package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    SpecGroupMapper specGroupMapper;

    @Autowired
    SpecParamService specParamService;

    @Override
    public List<SpecGroupDTO> listSpecGroupByCategoryId(Long cid) {
        List<SpecGroup> specGroupList = this.query().eq("category_id", cid).list();
        return SpecGroupDTO.convertEntityList(specGroupList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        this.save(specGroupDTO.toEntity(SpecGroup.class));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        this.updateById(specGroupDTO.toEntity(SpecGroup.class));
    }

    @Override
    public List<SpecGroupDTO> listSpecList(Long cid) {
        //return specGroupMapper.listSpecList(cid);
        List<SpecGroupDTO> specGroupDTOList = listSpecGroupByCategoryId(cid);
        List<SpecParamDTO> specParamDTOList = specParamService.listSpecParam(cid, null, null);
        Map<Long, List<SpecParamDTO>> map = specParamDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        specGroupDTOList.forEach(specGroupDTO -> {
            specGroupDTO.setParams(map.get(specGroupDTO.getId()));
        });
        return specGroupDTOList;
    }
}